﻿using System;
using System.Web.Mvc;
using Flagwind.Common;
using Flagwind.Resources;
using Flagwind.Runtime.Serialization;

namespace Flagwind.Web
{
	/// <summary>
	/// 表示一个以 JSON 格式为载体的接口响应类。
	/// </summary>
	public class ApiResult : ActionResult
	{
		#region 私有字段

		private readonly JsonResult _result = new JsonResult();

		#endregion

		#region 公共属性

		/// <summary>
		/// 获取或者设置响应状态码。
		/// </summary>
		public int Code
		{
			get;
			private set;
		}

		/// <summary>
		/// 获取或设置响应消息。
		/// </summary>
		public string Message
		{
			get;
			private set;
		}

		/// <summary>
		/// 获取或设置响应数据。
		/// </summary>
		public object Content
		{
			get;
			set;
		}

		/// <summary>
		/// 获取或设置服务器当前时间。
		/// </summary>
		public DateTime ServerTime
		{
			get;
			private set;
		}

		/// <summary>
		/// 获取或者设置序列化器配置。
		/// </summary>
		[SerializationMember(SerializationMemberBehavior.Ignored)]
		public TextSerializationSettings SerializerSettings
		{
			get;
			set;
		}

		#endregion

		#region 构造方法

		public ApiResult(ApiStatusCode code, object content = null, string message = null)
		{
			var entry = code.GetEnumEntry();

			this.Code = Flagwind.Common.Convert.ConvertValue<int>(ResourceUtility.GetString(entry.Alias));
			this.Message = message ?? ResourceUtility.GetString(entry.Description);
			this.Content = content;
			this.ServerTime = DateTime.Now;
		}

		public ApiResult(int code, string message = null)
		{
			this.Code = code;
			this.Message = message;
		}

		#endregion

		#region 重写方法

		public override void ExecuteResult(ControllerContext context)
		{
			_result.Data = this;
			_result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
			_result.SerializerSettings = this.SerializerSettings ?? TextSerializationSettings.Default;
			_result.ExecuteResult(context);
		}

		#endregion
	}
}
